package com.yf.realms;

import com.yf.entity.Employee;
import com.yf.entity.Role;
import com.yf.service.EmployeeService;
import com.yf.service.RoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleService roleService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> roles = new HashSet<>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String empName = principalCollection.getPrimaryPrincipal().toString();
        Employee employee = employeeService.getEmployeeByName(empName);
        Role role = roleService.getRoleByRoleId(employee.getRoleId());
        System.out.println(role);

        roles.add(role.getRoleName());
        info.setRoles(roles);
        return info;
    }




    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        System.out.println("认证1。。。。");
        String empName = token.getPrincipal().toString();
        System.out.println("认证2。。。。");
        Employee employee = employeeService.getEmployeeByName(empName);
        System.out.println(employee);
        if (employee==null){
            System.out.println("sss");
            return null;
        }
        ByteSource salt = ByteSource.Util.bytes(employee.getSalt());
        System.out.println(salt);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee.getEmpName(),employee.getEmpPassword(),salt,getName());
        System.out.println(employee.getEmpPassword());
        return info;
    }
}
